const path=require('path');
const express=require('express');
const multer=require('multer');
const app=express();

const upload=multer({
    storage:multer.diskStorage({
        destination:(req,file,cb)=>cb(null,'./uploads'),
        filename:(req,file,cb)=>{
            console.log('username:',req.query.username);
            cb(null,Date.now()+'-'+file.originalname)
        }
    })
});

//单个文件上传
app.get('/single',(req,res,next)=>{
   res.sendFile(path.resolve(__dirname,'./views/single.html'));
});

app.post('/single',upload.single('avatar'),(req,res)=>{
    console.log('Single req.file:',req.file);
    res.json({
        code:'0000',
        type:'single',
        originalname:req.file.originalname
    });
});


//多个文件上传
app.get('/multer',(req,res)=>{
    res.sendFile(path.resolve(__dirname,'./views/multer.html'));
});

app.post('/multer',upload.array('photos'),(req,res)=>{
   console.log('Multer req.files:',req.files);
   let files=[];
   req.files.map(file=>{
       files.push({originalname:file.originalname});
   });
   res.json({
       code:'0000',
       type:'multer',
       files
   });
});

//混合上传
app.get('/mix',(req,res)=>{
    res.sendFile(path.resolve(__dirname,'./views/mix.html'));
});
app.post('/mix',upload.fields([{name:'avatar'},{name:'photos'}]),(req,res)=>{
    console.log('Mix req.files:',req.files);
    let files=[];
    for(let field in req.files){
        req.files[field].forEach(file=>{
            files.push({originalname:file.originalname})
        });
    }
    res.json({
        colde:'0000',
        type:'Mix',
        files
    });
});

//Listen
app.listen(4000,()=>{
    console.log('----------------Multer @port 4000',new Date());
});